#define __LIBRARY__  
#include <unistd.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <asm/segment.h>
#include <asm/system.h>

#define SEM_NAME_LEN    20
#define SEMTABLE_LEN    20
sem_t semtable[SEMTABLE_LEN];
int last_sem = 0;

sem_t *sys_sem_open(const char *name,unsigned int value)
{
    char tmp_name[SEM_NAME_LEN+1]; 
    int i=0;
    int name_cnt=0;
    if(last_sem > SEMTABLE_LEN) return NULL;
    while( (tmp_name[name_cnt]=get_fs_byte(name+name_cnt)) != '\0'){
        name_cnt++;
        if(name_cnt>SEM_NAME_LEN)
            return NULL;
    }

    for(i=0;i<last_sem;i++)
        if(strcmp(tmp_name,semtable[i].name) == 0)
            return &semtable[i];

    semtable[last_sem].value = value;
    for(i=0;i<name_cnt;i++)
        semtable[last_sem].name[i]=tmp_name[i];
    return &semtable[last_sem++];
}


int sys_sem_wait(sem_t *sem)
{
    cli();
    while( sem->value == 0 ) 
        sleep_on(&(sem->queue));    
    sem->value--;             
    sti();
    return 0;
}
int sys_sem_post(sem_t *sem)
{
    cli();
    wake_up(&(sem->queue));
    sem->value++;
    sti();
    return 0;
}

int sys_sem_unlink(const char *name)
{
   char tmp_name[SEM_NAME_LEN+1]; 
    int i=0;
    int name_cnt=0;
    if(last_sem > SEMTABLE_LEN) return -1;
    while( (tmp_name[name_cnt]=get_fs_byte(name+name_cnt)) != '\0'){
        name_cnt++;
        if(name_cnt>SEM_NAME_LEN)
            return NULL;
    }
    for(i=0;i<last_sem;i++)
        if(strcmp(tmp_name,semtable[i].name) == 0){
            while(i<=last_sem-1)
                semtable[i]=semtable[i+1],i++;
            last_sem--;
            return 0;
        }
    return -1;
}